var millName; //染厂名称
var clientName; //客户名称
var millData = [];
var openID;
var hgS2;
var Judge_plan;
var code = getQueryString("code");

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}



$(function () {

    var etime = new Date();
    //$('#appDateTime').val(formatterSDate(etime));
    $('#appDateTime').val(getDay(0));
    $('#appDateTime02').val(formatterEDate(etime));
    //获取登录用户的权限和对应显示的数据
    getopenid();

});

function getopenid() {
    console.log(
        'https://www.xdfznh.club/wxpadbe/switch/oao/'
        + code);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/switch/oao/'
            + code,
        type: 'get',
        dataType: 'json',
        // 成功回调
        success: function (data) {
            console.log('请求成功');
            openID = data.data;
            console.log('openID=' + openID);
            getmill();
        },
        //失败回调
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //查看错误信息
            console.log('失败回调');
            console.log(XMLHttpRequest.status);
            console.log(XMLHttpRequest.readyState);
            console.log(textStatus);
        }
    })
}


//获取微信号对应的染厂名称
function getmill() {

    console.log('https://www.xdfznh.club/wxpadbe/client/' + openID);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/client/'
            + openID,

        type: 'get',
        dataType: 'json',
        success: function (data) {
            console.log(data.length);

            if (data.length == 0) {
                // 关闭当前页面
                alert('当前用户没有权限！');
            }

            if (data.length > 0) {
                millName = data[0].clients.split("-")[0]; //获取染厂名称
                // clientName = data[0].clients.split("-")[1];
                clientName = getClientNameKXD(data[0].clients);
                
                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].clients;

                    //console.log(data[n].mill);
                }
                ;
                getJurisdiction(); //获取个人查看报表的权限
                getDropDownDate(); // 设置下拉

            };
        }
    })
};

//获取个人查看报表的权限
function getJurisdiction() {
    console.log('https://www.xdfznh.club/wxpadbe/dynamicDS/query/'
        + 'select customer_inout FROM sys_userpermission where openid='
        + "'" +openID  + "' and client_name="
        + "'" + clientName + "' and mill="
        + "'" + millName + "'");

    console.log(millName);

    $.ajax({

        url: 'https://www.xdfznh.club/wxpadbe/dynamicDS/query/'
            + 'select customer_inout FROM sys_userpermission where openid='
            + "'" +openID  + "' and client_name="
            + "'" + clientName + "' and mill="
            + "'" + millName + "'",

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                //millName = data[0].mill;
                var cp = eval('(' + data[0].customer_inout + ')');  /*成品白坯*/

                if (cp==1) {
                    Judge_plan = true;
                    getData();

                } else {
                    Judge_plan = false;
                    alert('当前用户没有查看在成品白坯权限！');
                }

                getDropDownDate(); // 设置下拉

            } else {
                Judge_plan = false;

                alert('当前用户没有查看报表权限！');
            }
            ;
        }
    })

};


function getData() {
    console.log('https://www.xdfznh.club/wxpadbe/execute/query/'
        + millName
        + "/call ClientStock('"
        + document.getElementById("appDateTime").value.substr(0, 10)
        + "','"
        + document.getElementById("appDateTime02").value.substr(0, 10)
        + "','" + clientName +"')");

    $(".buttom").attr("disabled",true);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName
            + "/call ClientStock('"
            + document.getElementById("appDateTime").value.substr(0, 10)
            + "','"
            + document.getElementById("appDateTime02").value.substr(0, 10)
            + "','" + clientName +"')",

        type: 'get',
        dataType: 'json',
        success: function (data) {
            $('#waterdetai').datagrid('loadData', data);

        },
        complete: function(XMLHttpRequest, textStatus) {
            $(".buttom").attr("disabled",false);
        }
    })
};

/******************************************************************************************/

//查询事件
function getquery() {
    if (Judge_plan == true) {
        getData();

    }
}

/*设置时间格式*/
function add0(m) {
    return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

formatterSDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + day /*+ " " + "07" + ":" + "00"*/;
};

formatterEDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    var hor = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
    var min = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
    ;
    var sec = date.getSeconds();
    return date.getFullYear() + '-' + month + '-' + day /*+ " " + hor + ":" + "00"*/;
};


/*****************************************************************************************/

/*自定义本月日期时间*/
customSDateMonth = function (date) {
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month ;
};

//计算当前日期的前后几天的日期
function getDay(day) {
    var today = new Date();
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear + "-" + tMonth + "-" + tDate;  // + " " + "07" + ":" + "00"
}

function doHandleMonth(month) {
    var m = month;
    if (month.toString().length == 1) {
        m = "0" + month;
    }
    return m;
}

/*查询昨日的日期设置*/
function getYesterday() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-1));
    $('#appDateTime02').val(getDay(-1));

    getquery();
}

/*查询本日的日期设置*/
function getToday() {
    var etime = new Date();
    $('#appDateTime').val(getDay(0));
    $('#appDateTime02').val(getDay(0));

    getquery();
}

/*查询一周的日期设置*/
function getWeekdate() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-7));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}

/*查询一个月的日期设置*/
function getOneMonthdate() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-30));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}

/*查询本月的日期设置*/
function getMonthdate() {
    var etime = new Date();
    $('#appDateTime').val(customSDateMonth(etime));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}

/*************************************************************/


//设置染厂下拉
function getDropDownDate() {
    //console.log('2=' + millData);
    hgS2 = new selectSwiper({
        el: '.select_box2',
        mustSelect: true,
        activeIndex: 0,
        data: millData,
        init: function (index) {
            if (index !== -1) {
                $('.btn2').html(this.data[index]);
            }
        },
        okFunUndefind: function () {
            alert('必须选择一项');
        },
        okFun: function (index) {
            $('.btn2').html(this.data[index]);
            millName = $('button').text().split("-")[0];
            // clientName = $('button').text().split("-")[1];
            clientName = getClientNameKXD($('button').text());
            getJurisdictionmill();

        },
        closeFun: function () {
            console.log('取消');
        },
    });

    $('.btn2').on('click', function () {
        hgS2.openSelectSwiper();

    });
}

//在更换染厂之后  重新刷新数据  并判断个人权限
function getJurisdictionmill() {
    console.log('https://www.xdfznh.club/wxpadbe'
        + '/perm/selectBoss/'
        + openID + '/'
        + millName);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/dynamicDS/query/'
            + 'select customer_inout FROM sys_userpermission where openid='
            + "'" +openID  + "' and client_name="
            + "'" + clientName + "' and mill="
            + "'" + millName + "'",

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                var cp = eval('(' + data[0].customer_inout + ')');

                if (cp==1) {
                    Judge_plan = true;
                    getData();

                } else {
                    Judge_plan = false;
                    alert('当前用户没有查看在生产订单权限！');
                }

            } else {
                Judge_plan = false;
                alert('当前用户没有查看报表权限！');
            }
            ;
        }
    })

}


//获取标签下网格被选中的行的数据
function getClientName() {
   var Sdate=document.getElementById("appDateTime").value.substr(0, 10);
   var Edate=document.getElementById("appDateTime02").value.substr(0, 10);
    var type;


    var selected1 = $('#waterdetai').datagrid('getSelected');
    if (selected1 == undefined) {
        //   未选择
        alert("未选择订单，无法查询明细！");
        console.log(0);
        return;
    }


    type = selected1.typename;

    if(type=='白坯发染厂') {
        location.href = 'html/ClientStockdetail01.html' + '?clientname=' + clientName
            + '&'
            + 'type=' + type
            + '&'
            + 'Sdate=' + Sdate
            + '&'
            + 'Edate=' + Edate
            + '&'
            + 'millName=' + millName;
    }
    if(type=='染厂白坯库存') {
        location.href = 'html/ClientStockdetail02.html' + '?clientname=' + clientName
            + '&'
            + 'type=' + type
            + '&'
            + 'Sdate=' + Sdate
            + '&'
            + 'Edate=' + Edate
            + '&'
            + 'millName=' + millName;
    }
    if(type=='本期生产成品') {
        location.href = 'html/ClientStockdetail03.html' + '?clientname=' + clientName
            + '&'
            + 'type=' + type
            + '&'
            + 'Sdate=' + Sdate
            + '&'
            + 'Edate=' + Edate
            + '&'
            + 'millName=' + millName;
    }
    if(type=='染厂发成品') {
        location.href = 'html/ClientStockdetail04.html' + '?clientname=' + clientName
            + '&'
            + 'type=' + type
            + '&'
            + 'Sdate=' + Sdate
            + '&'
            + 'Edate=' + Edate
            + '&'
            + 'millName=' + millName;
    }
    if(type=='染厂成品库存') {
        location.href = 'html/ClientStockdetail05.html' + '?clientname=' + clientName
            + '&'
            + 'type=' + type
            + '&'
            + 'Sdate=' + Sdate
            + '&'
            + 'Edate=' + Edate
            + '&'
            + 'millName=' + millName;
    }


    // $("#buttom").attr("href",strhref);

}


// 2022年4月23日 14:56:47 chanchaw
// 白玉兰给凯欣达分为：凯欣达-1，凯欣达-2，凯欣达-3
// 微信->客户云->染厂已排计划    上面选择客户的按钮的 caption是：白玉兰-凯欣达-1
// 按照之前的逻辑获取客户名只能获取到：凯欣达
// 导致无法查询到指定客户的计划，本方法将后面所有的内容拼接返回正确的客户名
function getClientNameKXD(clientString){
    const clientStr = String(clientString)
    if(!clientStr || clientStr.length<=0) return '';

    const clientArray = clientStr.split('-');
    let ret = '';
    for(let i=1;i<clientArray.length;i++){
        ret = ret + clientArray[i] + '-'
    }

    ret = ret.substring(0,ret.length-1)
    return ret;
}
